<?php
/**
 * Display a Frame
 */
use Fox\Core\Errors;
use Fox\Html\Input;
use Fox\Generator;
use Fox\Html\Html;
use Fox\Html\Button;
use Fox\Popup;
use Fox\Msg;
use Nawa\Customer;
use Fox\Common\Contact;
use Fox\Dao\SqlFragment;
use Fox\Document\Type;
use Fox\Html\Input\File;
use Fox\Html\DropList;
use Fox\Html\Block;
use Fox\Html\Screen;

$xview = Xview::instance();
// Options
$className = $xview->val('classname');
$inLineId = $xview->val('inlineid');
if(empty($className))
{
	$xview->accessDenied();
}
$grouping = $className::DOC_GROUPING;

$screen = new Screen('sDocument','import');
$block = new Block('bDocument');

// Doc Type
$finder = new Type();
$types = $finder->find(new SqlFragment("category = ?",array($grouping)));
$block->add(new DropList('doctype',true,false,true))->options($types,'doctype','description');
// File Name
$block->add(new File('filename',true));
// Store Object & Inline Id
$block->add(new Input('inlineid',true,$inLineId))->hidden();
$block->add(new Input('classname',true,$className))->hidden();
$screen->add($block)->noLegend();

if($screen->submitted())
{
	$fields = $screen->get();
	if(!$screen->errors())
	{
		try {
			$now = new DateTime();
			$object = Fox\Dao::load($className,$inLineId);
			$fileName = \Xview::moveFileToServer();
			// Create Document Object
			$document = new \Fox\Document();
			$data['filename'] = $fileName['filename'];
			$data['destination'] = _TEMP_;
			$data['language'] = $xview->language();
			$data['doctype'] = $fields['doctype'];
			$data['physicalname'] = $fileName['physicalname'];
			$document->setFields($data);
			$document->create();
			// Add Document into the passed Object
			$resData['docid'] = $document->getId();
			$resData['doctype'] = $fields['doctype'];
			$resData['udate'] = $now->format(\Fox\Object::CORE_SQL_DATETIME_FORMAT);
			$resData['uname'] = User::current()->getId();
			$documentLink = $object->findDocuments(null);
			$documentLink->setFields($resData);
			$object->addToDocuments($documentLink);
			if($object instanceof \Fox\Object\Versioned)
			{
				$object->prepareUpdate($object::CHANGE_DOCUMENTS);
			}
			$object->update();
			// Add document to the search engine
			/*
			 $searchEngine = new \Fox\SearchEngine();
			 $searchEngine->add($document,$customer->getId(),Customer::classname());
			 */
		}
		catch (Fox\Object\Exception\Save $e)
		{
			Errors::generateMessage($e);
		}

	}
}
$popup = new Popup('pAddDocument',Msg(Msg::BUNDLE,Msg::TITLE_ADD_DOCUMENT),$screen,500);
$screen->ajaxUpload(Generator::ajaxReload('MC_documents'));
echo $popup->display();